# Create your views here.
import hashlib
import random

from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from pandas._libs import json

from .models import Question, Choice, Assets, UserRisk, Finance
from django.shortcuts import render, get_object_or_404
from django.urls import reverse
from django.views import generic




# def index(request):
#     latest_question_list = Question.objects.order_by('-pub_date')[:5]
#     # template = loader.get_template('taa/index.html')
#     context = {
#         'latest_question_list': latest_question_list
#     }
#     # return HttpResponse(template.render(context, request))
#     return render(request, 'taa/index.html', context)
#
# def detail(request, question_id):
#     # try:
#     #     question = Question.objects.get(pk=question_id)
#     # except Question.DoesNotExist:
#     #     raise Http404("Question does not exist")
#     # return render(request, 'polls/detail.html', {'question': question})
#
#     question = get_object_or_404(Question, pk=question_id)
#     return render(request, 'taa/detail.html', {'question': question})
#
# def results(request, question_id):
#     question = get_object_or_404(Question, pk=question_id)
#     return render(request, 'taa/results.html', {'question': question})

class IndexView(generic.ListView):
    template_name = 'taa/index.html'
    context_object_name = 'latest_question_list'

    def get_queryset(self):
        """Return the last five published questions."""
        return Question.objects.order_by('id')


class DetailView(generic.DetailView):
    model = Question
    template_name = 'taa/detail.html'


class ResultsView(generic.DetailView):
    model = Question
    template_name = 'taa/results.html'


def RiskView(request, risk_num):
    investType = getInvestType(risk_num)

    return render(request, "taa/risk.html", {
        'investType': investType,
        'risk_num': risk_num
    })


def getInvestType(risk_num):
    risk_num = int(risk_num)
    investType = "保守型"
    if risk_num <= 20 and risk_num > 16:
        investType = "稳健型"
    elif risk_num <= 25 and risk_num > 21:
        investType = "平衡型"
    elif risk_num <= 30 and risk_num > 26:
        investType = "进取型"
    elif risk_num <= 40 and risk_num > 31:
        investType = "激进型"
    return  investType

@csrf_exempt
def setRiskData(request):
    result = {"status": "error", "content": "错误", "rowkey": "A001"}
    if request.method == "POST":
        postBody = request.body

        data = json.loads(postBody)
        user = UserRisk()
        user.mobile_numer = data.get('mobile_numer')
        user.risk_num = data.get('risk_num')
        rowkey = setRowkey(data.get('csrfmiddlewaretoken'))
        user.rowkey = rowkey

        user.save()  # 保存到数据库

        result["status"] = "success"
        result["rowkey"] = rowkey
        result["content"] = "数据保存成功"

    else:
        result["content"] = "请求类型错误"
    return JsonResponse(result)


# 生成一个唯一值
def setRowkey(oldStr):
    md5 = hashlib.md5()
    randStr = random.choice('abcdefghijklmnopqrstuvwxyz!@#$%^&*()')
    newStr = randStr + oldStr
    md5.update(newStr.encode("utf-8"))
    result = md5.hexdigest()
    return result


def financeView(request, rowkey):
    template_name = "taa/finance.html"

    latest_finance_list = Assets.objects.order_by('id')

    return render(request, template_name, {
        'rowkey': rowkey,
        'latest_finance_list': latest_finance_list,
    })


@csrf_exempt
def setFinanceData(request):
    result = {"status": "error", "content": "请求过来了", "rowkey": "A001"}
    if request.method == "POST":
        postBody = request.body

        data = json.loads(postBody)

        for val in data["res"]:
            finance = Finance()
            finance.assets_score = data["res"][val]
            finance.assets_id = val
            finance.rowkey = data["rowkey"]
            finance.save()  # 保存到数据库
        result["status"] = "success"
        result["content"] = "数据保存成功"

    else:
        result["content"] = "请求类型错误"
    return JsonResponse(result)


def echarts(request, rowkey):
    template_name = "taa/echarts.html"
    assets_data = Assets.objects.values("id", "assets_question")
    finance_data = Finance.objects.filter(rowkey=rowkey).all().values("assets_score", "assets_id")
    user_data = UserRisk.objects.filter(rowkey=rowkey).values("mobile_numer", "risk_num")

    portfilo = {'保守型':[50, 50, 0, 0], '稳健型':[40, 50, 10, 0,], "平衡性":[30, 40, 20, 10], "进取型":[20, 40, 20, 20], "激进型":[10, 30, 30, 30]}


    investType = getInvestType(user_data[0]["risk_num"])
    assets_list = {}
    series = []
    legend = []
    for assetsVal in assets_data:
        assets_list[assetsVal["id"]] = assetsVal["assets_question"]
    sum = 0
    index1 = 0
    index2 = 0
    index3 = 0
    index4 = 0

    for val in finance_data:
        finance_list = {}
        finance_list["value"] = int(val["assets_score"])
        finance_list["name"] = assets_list.get(val["assets_id"])
        if finance_list["name"] == "银行存款" or finance_list["name"] == "货币型基金" or finance_list["name"] == "保险" or \
                        finance_list["name"] == "国债":
            index1 = index1 + int(val["assets_score"])
        elif finance_list["name"] == "银行理财产品" or finance_list["name"] == "信托产品":
            index2 = index2 + int(val["assets_score"])
        elif finance_list["name"] == "债券型基金及相关产品" or finance_list["name"] == "配置型基金及相关产品" or finance_list[
            "name"] == "股票型基金及相关产品":
            index3 = index3 + int(val["assets_score"])
        elif finance_list["name"] == "黄金" or finance_list["name"] == "股票" or finance_list["name"] == "期货" or \
                        finance_list["name"] == "外汇" or finance_list["name"] == "收藏及其他":
            index4 = index4 + int(val["assets_score"])

        if finance_list["value"] != 0:
            series.append(finance_list)
            legend.append(assets_list.get(val["assets_id"]))
            sum = sum + int(val["assets_score"])


    item = ["无风险收益", "低风险收益", "中等风险收益", "高风险收益"]
    lixiang = portfilo.get(investType)
    bardata=[round(index1/sum*100,2),round(index2/sum*100,2),round(index3/sum*100,2),round(index4/sum*100,2)]
    bardata2=[round(index1/sum*100,2)-lixiang[0],round(index2/sum*100,2)-lixiang[1],round(index3/sum*100,2)-lixiang[2],round(index4/sum*100 -lixiang[3], 2)]


    return render(request, template_name, {
        'rowkey': rowkey,
        'series': series,
        'legend': legend,
        'bardata': bardata,
        'bardata2': bardata2,
        'zipped_list': zip(item, bardata, lixiang, bardata2 ),
        'investType': investType


    })


def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the question voting form.
        return render(request, 'taa/detail.html', {
            'question': question,
            'error_message': "You didn't select a choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
        return HttpResponseRedirect(reverse('taa:results', args=(question.id,)))
